const {
  friendshipAssociationMemberList
} = require('../../../api/fraternity');
const {
  filePreview,
  getBase64
} = require('../../../api/index');
const {
  isFinished,
  sliceString,
  joinBase64
} = require('../../../utils/util');

// pages/fraternity/index/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    page: {
      pageNumber: 1,
      pageSize: 7,
      friendshipAssociationId: ''
    },
    total: 0, //  总条数
    finished: false,
    list: []
  },
  loadMore() { //  加载更多
    fetchFriendshipAssociationList.call(this);
  },
  onClick(event) {
    const {
      url
    } = event.currentTarget.dataset;
    wx.navigateTo({
      url
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const {
      id
    } = options;
    fetchFriendshipAssociationList.call(this, id);
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },
})


//  获取 联谊会列表数据
async function fetchFriendshipAssociationList(id) {
  this.data.page.friendshipAssociationId = id;

  wx.showLoading({
    title: '加载中...'
  });
  const {
    errors,
    result,
    totalCount
  } = await friendshipAssociationMemberList(this.data.page);
  if (errors.lenght > 0) {
    return;
  }

  //  判断数据是不是都已经加载完了
  this.setData({
    finished: isFinished(totalCount, this.data.page.pageNumber * this.data.page.pageSize)
  });
  //  加载更多数据
  this.setData({
    list: await setResult(result)
  });
  this.data.page.pageNumber++;

  wx.hideLoading();
}

//  处理数据
async function setResult(data = []) {
  const _data = JSON.parse(JSON.stringify(data));
  const person = {
    '1': '（会长）',
    '2': '（副会长）'
  };

  await Promise.all(_data.map(async _s => {
    const avatar = joinBase64(await getBase64(_s.avatar));
    _s.avatar = avatar;
    _s.presidentFlagName = person[_s.presidentFlag];
    return _s;
  }))

  return _data;;
}